<template>
	<div class="content-box add-good-argument">
		<el-form ref="formRef" class="good-service-form" :model="form" :rules="rules" label-width="100px">
			<el-form-item label="模板名称" prop="name">
				<el-input v-model="form.name" :maxlength="50" />
			</el-form-item>

			<el-form-item label="计费方式" prop="chargingType">
				<el-radio-group v-model="form.chargingType" class="w-full">
					<el-radio value="0"> 按件数 </el-radio>
				</el-radio-group>
			</el-form-item>

			<el-form-item label="区域运费" prop="details">
				<el-button type="primary" link class="mb15 mt6" @click="addDetailItem()">+ 新增配送区域</el-button>
				<el-table class="form-table" :data="form.details">
					<el-table-column label="配送区域" prop="areas" min-width="200" align="center">
						<template #default="{ row }">
							{{ row.areasLabel.join('、') }}
						</template>
					</el-table-column>
					<el-table-column label="首件" prop="first" align="center">
						<template #default="{ row, $index }">
							<el-form-item :prop="`details[${$index}].first`" :rules="rules.first" :label-width="1">
								<el-input-number :precision="0" :controls="false" :min="0" :max="999999999" v-model="row.first" :step="0" />
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column label="运费(元)" prop="basicCost" align="center">
						<template #default="{ row, $index }">
							<el-form-item :prop="`details[${$index}].basicCost`" :rules="rules.basicCost" :label-width="1">
								<el-input-number :precision="2" :controls="false" :min="0" :max="999999999" v-model="row.basicCost" :step="0" />
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column label="每续件" prop="more" align="center">
						<template #default="{ row, $index }">
							<el-form-item :prop="`details[${$index}].more`" :rules="rules.more" :label-width="1">
								<el-input-number :precision="0" :controls="false" :min="0" :max="999999999" v-model="row.more" :step="0" />
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column label="增加运费(元)" prop="moreCost" align="center">
						<template #default="{ row, $index }">
							<el-form-item :prop="`details[${$index}].moreCost`" :rules="rules.moreCost" :label-width="1">
								<el-input-number :precision="2" :controls="false" :min="0" :max="999999999" v-model="row.moreCost" :step="0" />
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column label="操作" prop="order" align="center" min-width="100">
						<template #default="scope">
							<el-button type="primary" link @click="addDetailItem(scope)"> 编辑 </el-button>
							<el-button type="primary" link @click="delDetailItem(scope)"> 删除 </el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
			<el-form-item label="指定条件包邮" align="center">
				<el-checkbox-group class="freight-free" v-model="form.condition">
					<el-checkbox label="1" value="1"
						>满<el-form-item prop="amountFree" align="center">
							<el-input-number :precision="2" :controls="false" :min="0" :max="999999999" v-model="form.amountFree" :step="0" /> </el-form-item
						>件包邮</el-checkbox
					>
					<el-checkbox label="2" value="2"
						>满<el-form-item prop="moneyFree" align="center">
							<el-input-number :precision="2" :controls="false" :min="0" :max="999999999" v-model="form.moneyFree" :step="0" /> </el-form-item
						>元包邮</el-checkbox
					>
				</el-checkbox-group>
			</el-form-item>
			<el-form-item label-width="0">
				<div class="flex-start w-full">
					<el-button @click="back">取消</el-button>
					<el-button type="primary" v-debounce="onSubmit">保存</el-button>
				</div>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup lang="tsx" name="addGoodFreight">
import { FormRules, ElMessage, ElMessageBox, ElCascader } from 'element-plus';
import { ref, h, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { fetchCreateFreight, fetchUpdateFreight } from '/@/api/goods';
import { Session } from '/@/utils/storage';
import cityCascader from '/@/components/cityCascader/index.vue';
import { fenToYuan } from '/@/utils/commonFunction';
const route = useRoute();
const router = useRouter();

const formRef = ref();
const form = ref<any>({
	name: '',
	chargingType: '0',
	details: [],
});

const editId = ref();

const validateAmountFree = (rule: any, value: any, callback: any) => {
	if (form.value.condition && form.value.condition.includes('1') && !value) {
		callback(new Error('件数不能为空'));
	} else {
		callback();
	}
};
const validateMoneyFree = (rule: any, value: any, callback: any) => {
	if (form.value.condition && form.value.condition.includes('2') && !value) {
		callback(new Error('金额不能为空'));
	} else {
		callback();
	}
};

//校验规则
const rules = reactive<FormRules<any>>({
	name: [{ required: true, trigger: 'blur', message: '模板名称不能为空' }],
	chargingType: [{ required: true, trigger: 'blur', message: '计费方式不能为空' }],
	details: [{ required: true, trigger: 'blur', message: '区域运费不能为空' }],
	amountFree: [{ validator: validateAmountFree, trigger: ['change', 'blur'] }],
	moneyFree: [{ validator: validateMoneyFree, trigger: ['change', 'blur'] }],
	first: [{ required: true, trigger: 'blur', message: '首件不能为空' }],
	basicCost: [{ required: true, trigger: 'blur', message: '首件运费不能为空' }],
	more: [{ required: true, trigger: 'blur', message: '续件不能为空' }],
	moreCost: [{ required: true, trigger: 'blur', message: '续件运费不能为空' }],
});

const onSubmit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const params = { ...form.value };
			params.details = params.details.map((v: any) => {
				return { ...v, basicCost: v.basicCost * 100, moreCost: v.moreCost * 100 };
			});
			params.moneyFree = params.moneyFree * 100;
			const res = editId.value ? await fetchUpdateFreight(params) : await fetchCreateFreight(params);
			if (res.code == 200) {
				ElMessage.success(editId.value ? '编辑运费模板成功' : '新增运费模板成功');
				back();
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const back = () => {
	router.push('/goods/freight');
};

const addDetailItem = (scope?: any) => {
	let city: any = scope
		? scope.row.areas.map((v: any) => {
				const arr = [v.province];
				if (v.city) {
					arr.push(v.city);
				}
				if (v.district) {
					arr.push(v.district);
				}
				return arr;
			})
		: '';

	let cityLabel: any = '';
	ElMessageBox({
		title: '选择配送区域',
		customStyle: { width: '800px', maxWidth: '800px' },
		message: () =>
			h(cityCascader, {
				modelValue: city,
				style: 'width: 770px',
				clearable: true,
				overflow: true,
				collapseTags: true,
				maxCollapseTags: 20,
				'onUpdate:modelValue': (val: any) => {
					city = val;
				},
				'onUpdate:label': (val: string) => {
					cityLabel = val;
				},

				props: {
					multiple: true,
					formatLabel: (labels: any) => {
						return labels[0];
					},
					// checkStrictly: true,
				},
			}),
		beforeClose: (action: any, inst: any, done: any) => {
			if (action == 'confirm' && !city) {
				ElMessage.warning('请选择配送区域');
				return;
			} else {
				done();
			}
		},
	}).then(() => {
		if (city) {
			if (scope) {
				form.value.details[scope.$index] = {
					...form.value.details[scope.$index],
					area: city,
					areas: city.map((v: any) => ({
						province: v[0],
						city: v[1],
						district: v[2],
					})),
					areasLabel: cityLabel,
				};
			} else {
				form.value.details.push({
					area: city,
					areas: city.map((v: any) => ({
						province: v[0],
						city: v[1],
						district: v[2],
					})),
					areasLabel: cityLabel,
					first: 1,
					basicCost: 0,
					more: 1,
					moreCost: 0,
				});
			}
		}
	});
};

const delDetailItem = (scope: any) => {
	form.value.details.splice(scope.$index, 1);
};

onMounted(async () => {
	editId.value = route.params.id;
	if (editId.value) {
		const data = Session.get('freight-edit-row');
		if (data) {
			let condition = [];
			if (data.amountFree) {
				condition.push('1');
			}
			if (data.moneyFree) {
				condition.push('2');
			}
			const details = data.details.map((v: any) => {
				return {
					...v,
					areas: v.areas.map((v: any) => {
						return {
							province: v.province?.areaId,
							city: v.city?.areaId,
							district: v.district?.areaId,
						};
					}),
				};
			});
			form.value = {
				chargingType: '0',
				condition,
				...data,
				details,
				moneyFree: fenToYuan(data.moneyFree),
				// areasLabel:data.data.
			};
		}
	}
});
</script>

<style lang="scss">
.add-good-argument {
	.el-form-item {
		.el-input,
		.el-select,
		.el-input-number {
			width: 100%;
			max-width: 450px;
		}
	}
	.el-table {
		.el-form-item {
			width: 80%;
			max-width: 150px;
			margin: auto;
		}
	}
	.freight-free {
		.el-checkbox {
			display: flex;
			margin-bottom: 20px;
		}
		.el-checkbox__label {
			display: flex;
			align-items: center;
			.el-form-item {
				margin: 0 10px;
			}
		}
	}
}
</style>
